#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
void read_terminal(evutil_socket_t fd, short what, void *arg)
{
        //读终端中的数据
        char buf[1024] = {0};
        int len = read(fd, buf, sizeof(buf));
        //将数据发送给server
        struct bufferevent* bev = (struct bufferevent*) arg;
        bufferevent_write(bev, buf, len+1);
}
void read_cb(struct bufferevent *bev, void *ctx)
{
        //接收对方发过来的数据
        char buf[1024] = {0};
        bufferevent_read(bev, buf, sizeof(buf));
        printf("recv data: %s\n",buf);
}
void write_cb(struct bufferevent *bev, void *ctx)
{
        printf("我是一个没有什么用的函数\n");
}
void event_cb(struct bufferevent *bev, short what, void *ctx)
{
        if(what & BEV_EVENT_CONNECTED){
                printf("连接服务器成功\n");
                return ;
        }else if(what & BEV_EVENT_EOF){
                printf("连接断开\n");
                bufferevent_free(bev);
        }else if(what & BEV_EVENT_ERROR){
                printf("some other error\n");
                bufferevent_free(bev);
        }else{
                printf("others\n");
                bufferevent_free(bev);
        }
}
//终端接收输入,将数据发给server
int main(int argc, char const *argv[])
{
        struct event_base* base = event_base_new();

        //创建事件
        //连接服务器的 -- fd
        int fd = socket(AF_INET, SOCK_STREAM, 0);
        //fd -- bufferevent
        struct bufferevent* bev  = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
        //连接服务器
        struct sockaddr_in serv;
        memset(&serv,0, sizeof(serv));
        serv.sin_family = AF_INET;
        serv.sin_port = htons(8765);
        evutil_inet_pton(AF_INET,"127.0.0.1",&serv.sin_addr.s_addr);
        bufferevent_socket_connect(bev, (struct sockaddr *)&serv, sizeof(serv));
        //给缓冲区设置回调
        bufferevent_setcb(bev,read_cb, write_cb, event_cb,base);
        bufferevent_enable(bev, EV_READ | EV_WRITE);

        // 接收键盘输入
        //再创建一个新事件
        struct event* ev = event_new(base, STDIN_FILENO , EV_READ|EV_PERSIST, read_terminal, bev);
        //添加事件到event_base
        event_add(ev, NULL);

        //启动事件循环
        event_base_dispatch(base);

        //释放资源
        bufferevent_free(bev);
        event_free(ev);
        event_base_free(base);
        return 0;
}
